import { createRouter,createWebHashHistory } from "vue-router";
import RoutesConfig from './config'
import { useRouterStore } from "@/store/useRouterStore";


const routes = [
    {
        path:"/",
        redirect:"/index"
    },
    {
        path:"/login",
        name:"login",
        component:() => import('@/views/Login.vue')
    },
    {
        path:"/mainbox",
        name:"mainbox",
        component:() => import('@/views/MainBox.vue')
    }
]

const router = createRouter({
    history:createWebHashHistory(),
    routes
})


router.beforeEach((to,from,next)=>{
    const { isGetterRouter, getMenuInfoFromBackend, addRoutesFromMenuInfo,changeRouter  } = useRouterStore()
    if(to.name==="login"){
        next()
    }else{
        if(!localStorage.getItem("token")){
            next({
                path:"/login"
            })
        }else{
            if (!isGetterRouter) {
                // 先获取菜单信息
                getMenuInfoFromBackend().then(() => {
                    // 根据获取到的菜单信息生成动态路由
                    const dynamicRoutes = addRoutesFromMenuInfo();
                   
                    dynamicRoutes.forEach((route) => {
                        router.addRoute(route);
                    });
                    changeRouter(true);
                    next({
                        path: to.fullPath
                    });
                });
            } else {
                next();
            }
            
        }
    }
    
})

const ConfigRouter = ()=>{
    const {changeRouter} = useRouterStore()
    RoutesConfig.forEach(item=>{
        router.addRoute("mainbox",item)
    })

    changeRouter(true)
}


export default router